﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Business;
using System.Data.SqlClient;
using System.Web.Configuration;
using Models;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Collections;
using iTextSharp.text.xml;
using iTextSharp.text.html;
using DataAccess;

public partial class client_Vibration_Report : @base
{
    private ReportServices rs = new ReportServices();

    // private Client client = new Client();
    private PdfWriter writer;
    private ArrayList title = new ArrayList(3);
    private ArrayList infor = new ArrayList(16);
    private Paragraph pa;
    // private PdfPTable tableInfo = new PdfPTable(2);
    //bool changeSite = false, changeSeverity = false;
    // private DataTable severity = new DataTable();
    // private DataTable Sites = new DataTable();

    //UserServices user = new UserServices();
    //ReportServices report = new ReportServices();
    private int selectedClient_id;
    private int workorderID;

    private class headerfooter
    {
        private PdfPTable head;
        private PdfPTable foot;
        private iTextSharp.text.Image _img;
        private Font font;
        private String t1 = "i2iTechnologies PO Box 1192, Clevand Qld 4163, Australia";
        private String t2 = "Office (07) 3829 1235 Fax (07) 3829 1238 Mob: 0439 717 244 Web: www.i2i-technologies.com.au ";
        private String t3 = "@i2iTechnologies";

        public headerfooter()
        {
            head = new PdfPTable(1);
            foot = new PdfPTable(1);
            font = new Font();
            font.Color = BaseColor.BLUE;
            font.Size = 6f;
            font.SetFamily("Arial");
        }
        public PdfPTable Head
        {
            get { return head; }

        }
        public PdfPTable Foot
        {
            get { return foot; }

        }

        public void setHeader(String path, float width, int align, int border, int scale)
        {
            PdfPTable header = new PdfPTable(1);
            header.TotalWidth = width - 35;
            _img = iTextSharp.text.Image.GetInstance(path);
            _img.ScalePercent(scale);
            PdfPCell c = new PdfPCell(_img, false);

            c.HorizontalAlignment = align;
            c.Border = border;
            header.AddCell(c);
            head = header;

        }
        public void setFooter(float width)
        {

            PdfPTable footer = new PdfPTable(1);
            footer.TotalWidth = width;
            Chunk ck = new Chunk(t1, font);
            Phrase p1 = new Phrase(ck);

            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_CENTER;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_MIDDLE;

            fc.Rowspan = 1;
            footer.AddCell(fc);

            ck = new Chunk(t2, font);
            fc.Phrase = new Phrase(ck);
            fc.Rowspan = 1;
            footer.AddCell(fc);

            fc.Rowspan = 1;

            ck = new Chunk(t3, font);
            fc.Phrase = new Phrase(ck);
            footer.AddCell(fc);

            foot = footer;

        }
    }

    private class _events : PdfPageEventHelper
    {
        // private iTextSharp.text.Image _img;
        private String path;



        public _events(String p)
        {
            /*
            * create single instance so image bytes added **ONCE** to the PDF file,
            * instead of every time you start a new page
            */

            path = p + "/logo.png";
            //     _img = iTextSharp.text.Image.GetInstance(path + "/logo.png");

            /*
            * scale image to fit available space, if needed
            */
            //  _img.ScalePercent(50);
        }
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            Rectangle page = document.PageSize;

            headerfooter hfPage = new headerfooter();

            hfPage.setHeader(path, page.Width - 35, Element.ALIGN_RIGHT, Rectangle.NO_BORDER, 100);
            hfPage.setFooter(page.Width);
            PdfPTable head = hfPage.Head;
            PdfPTable foot = hfPage.Foot;


            /*
            * write header w/WriteSelectedRows(); requires absolute positions!
            */
            head.WriteSelectedRows(
               0, -1,          // first/last row; -1 flags all write all rows
               0, // left offset
                // ** bottom** yPos of the table
                // page.Height - document.TopMargin + head.TotalHeight,
              820,
               writer.DirectContent
             );


            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
        }
    }// end of Thao code
    protected void Page_Load(object sender, EventArgs e)
    {
        if (UserDetails == null)
        {
            string jscript = "<script language='javascript'  type='text/javascript'> parent.document.location.href= '../Default.aspx'</script>";
            //Page.RegisterClientScriptBlock("key2ClientBlock", jscript);
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "key3ClientBlock", jscript);

        }

        string currDate = Request.QueryString["date"];
        //string clientID2 = Request.QueryString["client_id"];
        //Session["client_id"] = clientID2;
        if (!IsPostBack)
        {
            workorderID = 0;

            String machineID = Request.QueryString["id"];
            Session["machineID"] = machineID;
            string query = "SELECT client_id FROM Sites WHERE site_id in "
                + "(SELECT site_id FROM Machines WHERE machine_id='" + machineID + "')";
            CreateConn objcon = new CreateConn();
            DataTable clientDT = objcon.SQLConnDataTable(query);
            foreach (DataRow dr in clientDT.Rows)
            {
                string clientID = dr["client_id"].ToString();
                Session["client_id"] = clientID;
            }
            BindComponentStatus(machineID);
            setDateList(ToInt(machineID));
            //"SELECT client_id FROM Sites WHERE site_id in (SELECT site_id FROM Machines WHERE machine_id='144')"
            //"SELECT client_id FROM Sites WHERE site_id in (SELECT site_id FROM Machines WHERE machine_id='144')"
            //"SELECT client_id FROM Sites WHERE site_id in (SELECT site_id FROM Machines WHERE machine_id='175')"
            // BindData(machineID);
            machineid.Text = machineID;

            //WODateTime.Text = DateTime.Now.ToString();
            //prev_wo.NavigateUrl = "Work_Orders.aspx?id=" + machineID;
            setClientList();
            int t = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByValue(currDate));
            DropDownList1.SelectedIndex = t;// DropDownListDate.Items.IndexOf(DropDownListDate.Items.FindByValue(currDate));

        }




    }
    protected void setClientList()
    {
        DataTable Clients = new DataTable();
        if (ClientDetails != null)
        {
            int parentClientID = ClientDetails.ParentClientID;
            if (parentClientID == 0)
            {
                Clients = rs.getClientsByParent(ClientDetails.ClientID);
                if (Clients.Rows.Count == 0)
                {
                    Clients.Rows.Add(ClientDetails.ClientName, ClientDetails.ClientID);
                }
            }
            else
            {
                Clients.Columns.Add("clientName", typeof(string));
                Clients.Columns.Add("client_id", typeof(int));
                Clients.Rows.Add(ClientDetails.ClientName, ClientDetails.ClientID);
                //    selectedClient = ClientDetails.ClientID;
            }
            int ok = 1;
            foreach (DataRow cl in Clients.Rows)
            {
                String clientName = cl["clientName"].ToString();
                String clientid = cl["client_id"].ToString();
                System.Web.UI.WebControls.ListItem clientitem = new System.Web.UI.WebControls.ListItem(clientName, clientid, true);
                DropDownClientList.Items.Add(clientitem);
                if (ok == 1)
                {
                    DropDownClientList.SelectedValue = clientid;
                    ok = 0;
                    selectedClient_id = ToInt(clientid);
                }
            }
            // selectedClient = ToInt(DropDownClientList.SelectedValue);
        }
        else
        {
            string jscript = "<script language='javascript'  type='text/javascript'> parent.document.location.href= '../Default.aspx'</script>";
            //Page.RegisterClientScriptBlock("key2ClientBlock", jscript);
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "key3ClientBlock", jscript);

        }
    }
    protected void setDateList(int machine_id)
    {
        DataTable Dates = new DataTable();
        Dates = rs.getDateByMachineID(machine_id);
        foreach (DataRow r in Dates.Rows)
        {
            string date = r["dateRecorded"].ToString();

            string dateDisplay = date.Substring(0, 10);
            // string dateName = date.Substring(0, 10);
            System.Web.UI.WebControls.ListItem ls = new System.Web.UI.WebControls.ListItem(dateDisplay, date, true);
            DropDownList1.Items.Add(ls);
        }

    }
    /*   protected void BindComponentStatus(String machineID)
       {
           CreateConn objcon = new CreateConn();
           try
           {
               string query = "SELECT siteName, machineName, photo" +
                       " FROM  Sites INNER JOIN" +
                       " Machines ON Sites.site_id = Machines.site_id" +
                       " WHERE (Machines.machine_id = " + machineID + ")";
               DataTable dt = objcon.SQLConnDataTable(query);

               sitename.Text = dt.Rows[0]["siteName"].ToString();
               machinename.Text = dt.Rows[0]["machineName"].ToString();

               //setting the Machine Image
               string path = Server.MapPath("../photos/" + dt.Rows[0]["photo"].ToString());
               System.Drawing.Image image = System.Drawing.Image.FromFile(path, true);
               ImageEditor objimg = new ImageEditor();
               int height = 0;
               int width = 0;
               if (objimg.isPortrait(image))
               {
                   height = 160;
                   width = 120;
               }
               else
               {
                   height = 120;
                   width = 160;
               }
              // machinePhoto.Attributes.Add("Width", Convert.ToString(width));
              // machinePhoto.Attributes.Add("Height", Convert.ToString(height));
              // machinePhoto.ImageUrl = "../photos/" + dt.Rows[0]["photo"].ToString();
               ImageButton1.Attributes.Add("Width", Convert.ToString(width));
               photoHyperLink.Attributes.Add("href", "../photos/" + dt.Rows[0]["photo"].ToString());
               ImageButton1.Attributes.Add("Height", Convert.ToString(height));
               ImageButton1.ImageUrl = "../photos/" + dt.Rows[0]["photo"].ToString();
            
               if (dt.Rows[0]["photo"].ToString() == "NotAvailable.jpg")
               {
                   photoHyperLink.Visible = false;
               }
           }
           catch (Exception err)
           {
               Console.Write("Err msg:" + err.Message);
           }
           try
           {
               string queryDate = String.Empty;
               string currDate = String.Empty;
               DataTable date_dt = new DataTable();
               DataTable prev_dt = new DataTable();

               string date = Request.QueryString["date"];
               if (date == null)
               {
                   objcon = new CreateConn();
                   queryDate = "SELECT TOP (1) dateEntered" +
                       " FROM (SELECT DISTINCT TOP (1) ComponentStatus.dateEntered" +
                               " FROM Components INNER JOIN" +
                               " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                               " WHERE   (Components.machine_id = '" + machineID + "')" +
                               " ORDER BY ComponentStatus.dateEntered DESC) AS data" +
                       " ORDER BY dateEntered";
                   date_dt = objcon.SQLConnDataTable(queryDate);
                   currDate = date_dt.Rows[0]["dateEntered"].ToString();
               }
               else
               {
                   currDate = date;
               }
               //for current component status
               objcon = new CreateConn();
               string component_query = "SELECT Components.componentName, ComponentStatus.status_id, ComponentStatus.comments, StandardComments.commentDescription" +
                   " FROM Components INNER JOIN" +
                   " ComponentStatus ON Components.component_id = ComponentStatus.component_id INNER JOIN" +
                   " StandardComments ON ComponentStatus.comment_id = StandardComments.comment_id" +
                   " WHERE (Components.machine_id = '" + machineID + "') AND (ComponentStatus.dateEntered = CONVERT(datetime, '" + currDate + "', 103))";
               DataTable component_dt = objcon.SQLConnDataTable(component_query);

               //for previous component status
               string prevDate = GetPreviousDate(machineID, currDate);
               objcon = new CreateConn();
               string prevcomponent_query = "SELECT ComponentStatus.status_id" +
                   " FROM Components INNER JOIN" +
                   " ComponentStatus ON Components.component_id = ComponentStatus.component_id INNER JOIN" +
                   " StandardComments ON ComponentStatus.comment_id = StandardComments.comment_id" +
                   " WHERE (Components.machine_id = '" + machineID + "') AND (ComponentStatus.dateEntered = CONVERT(datetime, '" + prevDate + "', 103))";
               DataTable prevcomponent_dt = objcon.SQLConnDataTable(prevcomponent_query);

               DropDownListDate.SelectedIndex = DropDownListDate.Items.IndexOf(DropDownListDate.Items.FindByValue(currDate));
               string currCol = "#666666";
               string prevCol = "#666666";
               ComponentName1.Text = component_dt.Rows[0]["componentName"].ToString();
               currCol = ConvertToColor(component_dt.Rows[0]["status_id"].ToString());
               string befDate = GetBeforeDate(machineID, currDate);
               CurrentLabel1.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
               if (currDate != prevDate)
               {
                   prevCol = ConvertToColor(prevcomponent_dt.Rows[0]["status_id"].ToString());
                   PreviousLabel1.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
               }
               CurrentLabel1.ForeColor = System.Drawing.Color.FromName(currCol);
               PreviousLabel1.ForeColor = System.Drawing.Color.FromName(prevCol);
               Description1.Text = component_dt.Rows[0]["commentDescription"].ToString() +
                   " - " + component_dt.Rows[0]["comments"].ToString();
               if (ComponentName1.Text != null)
               {
                   Component1.Visible = true;
               }
               if (ComponentName1.Text.ToString().EndsWith("box"))
               {
                   HyperLink1Oil.NavigateUrl = "oilreport.aspx";
                   HyperLink1Oil.Visible = true;
               }
               ComponentName2.Text = component_dt.Rows[1]["componentName"].ToString();
               currCol = ConvertToColor(component_dt.Rows[1]["status_id"].ToString());
               CurrentLabel2.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
               if (currDate != prevDate)
               {
                   prevCol = ConvertToColor(prevcomponent_dt.Rows[1]["status_id"].ToString());
                   PreviousLabel2.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
               }
               CurrentLabel2.ForeColor = System.Drawing.Color.FromName(currCol);
               PreviousLabel2.ForeColor = System.Drawing.Color.FromName(prevCol);
               Description2.Text = component_dt.Rows[1]["commentDescription"].ToString() +
                   " - " + component_dt.Rows[1]["comments"].ToString();
               if (ComponentName2.Text != null)
               {
                   Component2.Visible = true;
               }
               if (ComponentName2.Text.ToString().EndsWith("box"))
               {
                   HyperLink2Oil.NavigateUrl = "oilreport.aspx";
                   HyperLink2Oil.Visible = true;
               }
               ComponentName3.Text = component_dt.Rows[2]["componentName"].ToString();
               currCol = ConvertToColor(component_dt.Rows[2]["status_id"].ToString());
               CurrentLabel3.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
               if (currDate != prevDate)
               {
                   prevCol = ConvertToColor(prevcomponent_dt.Rows[2]["status_id"].ToString());
                   PreviousLabel3.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
               }
               CurrentLabel3.ForeColor = System.Drawing.Color.FromName(currCol);
               PreviousLabel3.ForeColor = System.Drawing.Color.FromName(prevCol);
               Description3.Text = component_dt.Rows[2]["commentDescription"].ToString() +
                   " - " + component_dt.Rows[2]["comments"].ToString();
               if (ComponentName3.Text != null)
               {
                   Component3.Visible = true;
               }
               if (ComponentName3.Text.ToString().EndsWith("box"))
               {
                   HyperLink3Oil.NavigateUrl = "oilreport.aspx";
                   HyperLink3Oil.Visible = true;
               }
               ComponentName4.Text = component_dt.Rows[3]["componentName"].ToString();
               currCol = ConvertToColor(component_dt.Rows[3]["status_id"].ToString());
               CurrentLabel4.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
               if (currDate != prevDate)
               {
                   prevCol = ConvertToColor(prevcomponent_dt.Rows[3]["status_id"].ToString());
                   PreviousLabel4.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
               }
               CurrentLabel4.ForeColor = System.Drawing.Color.FromName(currCol);
               PreviousLabel4.ForeColor = System.Drawing.Color.FromName(prevCol);
               Description4.Text = component_dt.Rows[3]["commentDescription"].ToString() +
                   " - " + component_dt.Rows[3]["comments"].ToString();
               if (ComponentName4.Text != null)
               {
                   Component4.Visible = true;
               }
               if (ComponentName4.Text.ToString().EndsWith("box"))
               {
                   HyperLink4Oil.NavigateUrl = "oilreport.aspx";
                   HyperLink4Oil.Visible = true;
               }
           }
           catch (Exception err)
           {
               Console.Write("Err msg:" + err.Message);
           }
       }
       */
    protected void BindComponentStatus(String machineID)
    {
        CreateConn objcon = new CreateConn();
        try
        {
            string query = "SELECT siteName, machineName, photo" +
                    " FROM  Sites INNER JOIN" +
                    " Machines ON Sites.site_id = Machines.site_id" +
                    " WHERE (Machines.machine_id = " + machineID + ")";
            DataTable dt = objcon.SQLConnDataTable(query);

            sitename.Text = dt.Rows[0]["siteName"].ToString();
            SITENAME = sitename.Text;
            machinename.Text = dt.Rows[0]["machineName"].ToString();
            Session["machinename"] = machinename.Text;
            Session["sitename"] = sitename.Text;
            //setting the Machine Image
            string path = Server.MapPath("../photos/" + dt.Rows[0]["photo"].ToString());
            System.Drawing.Image image = System.Drawing.Image.FromFile(path, true);
            ImageEditor objimg = new ImageEditor();
            int height = 0;
            int width = 0;
            if (objimg.isPortrait(image))
            {
                height = 160;
                width = 120;
            }
            else
            {
                height = 120;
                width = 160;
            }
            machinePhoto.Attributes.Add("Width", Convert.ToString(width));
            machinePhoto.Attributes.Add("Height", Convert.ToString(height));
            machinePhoto.ImageUrl = "../photos/" + dt.Rows[0]["photo"].ToString();
            photoHyperLink.Attributes.Add("href", "../photos/" + dt.Rows[0]["photo"].ToString());

            if (dt.Rows[0]["photo"].ToString() == "NotAvailable.jpg")
            {
                photoHyperLink.Visible = false;
            }
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        try
        {
            string queryDate = String.Empty;
            string currDate = String.Empty;
            DataTable date_dt = new DataTable();
            DataTable prev_dt = new DataTable();

            string date = Request.QueryString["date"];
            if (date == null)
            {
                objcon = new CreateConn();
                queryDate = "SELECT TOP (1) dateRecorded" +
                    " FROM (SELECT DISTINCT TOP (1) ComponentStatus.dateRecorded" +
                            " FROM Components INNER JOIN" +
                            " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                            " WHERE   (Components.machine_id = '" + machineID + "')" +
                            " ORDER BY ComponentStatus.dateRecorded DESC) AS data" +
                    " ORDER BY dateRecorded";
                date_dt = objcon.SQLConnDataTable(queryDate);
                currDate = date_dt.Rows[0]["dateRecorded"].ToString();
            }
            else
            {
                currDate = date;
            }
            //for current component status
            objcon = new CreateConn();
            /*    string component_query = "SELECT Components.componentName, ComponentStatus.status_id, ComponentStatus.comments, StandardComments.commentDescription" +
                    " FROM Components INNER JOIN" +
                    " ComponentStatus ON Components.component_id = ComponentStatus.component_id INNER JOIN" +
                    " StandardComments ON ComponentStatus.comment_id = StandardComments.comment_id" +
                    " WHERE (Components.machine_id = '" + machineID + "') AND (ComponentStatus.dateEntered = CONVERT(datetime, '" + currDate + "', 103))";
              */
            string component_query = "SELECT Components.componentName,components.component_id, ComponentStatus.status_id, ComponentStatus.comments" +
                                   " FROM            Components INNER JOIN" +
                                   " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                                   " WHERE        (Components.machine_id =" + machineID + ") AND (ComponentStatus.dateRecorded = CONVERT(datetime, '" + currDate + "', 101))";
            DataTable component_dt = objcon.SQLConnDataTable(component_query);

            //for previous component status
            string prevDate = GetPreviousDate(machineID, currDate);
            objcon = new CreateConn();
            string prevcomponent_query = "SELECT ComponentStatus.status_id" +
                " FROM Components INNER JOIN" +
                " ComponentStatus ON Components.component_id = ComponentStatus.component_id " +
                " WHERE (Components.machine_id = '" + machineID + "') AND (ComponentStatus.dateRecorded = CONVERT(datetime, '" + prevDate + "', 101))";
            DataTable prevcomponent_dt = objcon.SQLConnDataTable(prevcomponent_query);
            System.Web.UI.WebControls.ListItem index = DropDownListDate.Items.FindByValue(currDate);
            DropDownListDate.SelectedIndex = DropDownListDate.Items.IndexOf(index);
            string currCol = "#666666";
            string prevCol = "#666666";
            ComponentName1.Text = component_dt.Rows[0]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[0]["status_id"].ToString());
            string befDate = GetBeforeDate(machineID, currDate);
            CurrentLabel1.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[0]["status_id"].ToString());
                PreviousLabel1.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel1.ForeColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel1.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description1.Text = component_dt.Rows[0]["comments"].ToString();
            if (ComponentName1.Text != null)
            {
                Component1.Visible = true;
            }
            if (ComponentName1.Text.ToString().EndsWith("box"))
            {

                string component_id = component_dt.Rows[0]["component_id"].ToString();
                HyperLink1Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;
                HyperLink1Oil.Visible = true;
            }
            ComponentName2.Text = component_dt.Rows[1]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[1]["status_id"].ToString());
            CurrentLabel2.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[1]["status_id"].ToString());
                PreviousLabel2.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel2.ForeColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel2.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description2.Text = component_dt.Rows[1]["comments"].ToString();
            if (ComponentName2.Text != null)
            {
                Component2.Visible = true;
            }
            if (ComponentName2.Text.ToString().EndsWith("box"))
            {
                string component_id = component_dt.Rows[1]["component_id"].ToString();
                HyperLink2Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;
                HyperLink2Oil.Visible = true;
            }
            ComponentName3.Text = component_dt.Rows[2]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[2]["status_id"].ToString());
            CurrentLabel3.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[2]["status_id"].ToString());
                PreviousLabel3.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel3.ForeColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel3.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description3.Text = component_dt.Rows[2]["comments"].ToString();
            if (ComponentName3.Text != null)
            {
                Component3.Visible = true;
            }
            if (ComponentName3.Text.ToString().EndsWith("box"))
            {
                string component_id = component_dt.Rows[2]["component_id"].ToString();
                HyperLink3Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;
                HyperLink3Oil.Visible = true;
            }
            ComponentName4.Text = component_dt.Rows[3]["componentName"].ToString();
            currCol = ConvertToColor(component_dt.Rows[3]["status_id"].ToString());
            CurrentLabel4.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + befDate;
            if (currDate != prevDate)
            {
                prevCol = ConvertToColor(prevcomponent_dt.Rows[3]["status_id"].ToString());
                PreviousLabel4.NavigateUrl = "Vibration_Report.aspx?id=" + machineID + "&date=" + prevDate;
            }
            CurrentLabel4.ForeColor = System.Drawing.Color.FromName(currCol);
            PreviousLabel4.ForeColor = System.Drawing.Color.FromName(prevCol);
            Description4.Text = component_dt.Rows[3]["comments"].ToString();
            if (ComponentName4.Text != null)
            {
                Component4.Visible = true;
            }
            if (ComponentName4.Text.ToString().EndsWith("box"))
            {
                string component_id = component_dt.Rows[3]["component_id"].ToString();
                HyperLink4Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;
                HyperLink4Oil.Visible = true;
            }
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
    }

    protected string GetPreviousDate(string machineID, string date)
    {
        CreateConn objcon = new CreateConn();
        try
        {
            DateTime currdate = Convert.ToDateTime(date);
            string queryPrevDate = "SELECT DISTINCT ComponentStatus.dateRecorded" +
                " FROM Components INNER JOIN" +
                " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                " WHERE (Components.machine_id = " + machineID + ")" +
                " ORDER BY ComponentStatus.dateRecorded DESC";
            DataTable prev_dt = objcon.SQLConnDataTable(queryPrevDate);
            foreach (DataRow dr in prev_dt.Rows)
            {
                string thisdate = dr["dateRecorded"].ToString();
                DateTime prevdate = Convert.ToDateTime(thisdate);
                if (prevdate < currdate)
                {
                    date = thisdate;
                    break;
                }
            }
            //date = prev_dt.Rows[0]["dateEntered"].ToString();
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        return date;
    }

    protected string GetBeforeDate(string machineID, string date)
    {
        //Thao's code
        CreateConn objcon = new CreateConn();
        try
        {
            DateTime currdate = Convert.ToDateTime(date);
            string queryBefDate = "SELECT DISTINCT ComponentStatus.dateRecorded" +
                " FROM Components INNER JOIN" +
                " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                " WHERE (Components.machine_id = " + machineID + ")" +
                " ORDER BY ComponentStatus.dateRecorded ";
            DataTable bef_dt = objcon.SQLConnDataTable(queryBefDate);
            foreach (DataRow dr in bef_dt.Rows)
            {
                string thisdate = dr["dateRecorded"].ToString();
                DateTime befdate = Convert.ToDateTime(thisdate);
                if (befdate > currdate)
                {
                    date = thisdate;
                    break;
                }
            }
            //date = prev_dt.Rows[0]["dateEntered"].ToString();
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        return date;
    }

    protected string ConvertToColor(string col)
    {
        if (col == "2")
        {
            col = "#FFFF00";
        }
        else if (col == "3")
        {
            col = "#FF9900";
        }
        else if (col == "4")
        {
            col = "#FF0000";
        }
        else if (col == "1")
        {
            col = "#00FF00";
        }
        else
        {
            col = "#0000FF";
        }
        return col;
    }
    protected void DropDownList_IndexChanged(Object sender, EventArgs e)
    {
        string date = DropDownList1.SelectedValue.ToString();
        Server.Transfer("Vibration_Report.aspx?id=" + MACHINEID + "&date=" + date);

    }






    /*  protected string ConvertToColor(string col)
      {
          if (col == "Abnormal")
          {
              col = "#FFFF00";
          }
          else if (col == "Moderate")
          {
              col = "#FF9900";
          }
          else if (col == "Severe")
          {
              col = "#FF0000";
          }
          else
          {
              col = "#00FF00";
          }
          return col;
      }}*/

    //protected void submitButton_Click(object sender, EventArgs e)
    //{
    //    String frm_date_submitted = WODateTime.Text.ToString();
    //    String frm_description = WODescription.Text.ToString();
    //    String frm_workorder_reference_no = WONumber.Text.ToString();
    //    String frm_machine_id = machineid.Text.ToString();

    //    CreateConn objcon = new CreateConn();
    //    string query = "INSERT INTO WorkOrders (workorder_reference_no, machine_id, description, date_submitted)"
    //           + " values ('" + frm_workorder_reference_no + "'," + frm_machine_id + ",'" + frm_description + "','" + frm_date_submitted + "')";

    //    objcon.SQLCmd(query);

    //    wo_message.Text = "Work Order: " + WONumber.Text.ToString() + " Successfully created";
    //    WODescription.Text = "";
    //    WONumber.Text = "";
    //}
    protected PdfPTable setLegendTable(float width)
    {
        PdfPTable legendTable = new PdfPTable(2);
        // legendTable.TotalWidth = width+30;
        legendTable.SetTotalWidth(new float[] { 25, 170 });
        legendTable.WidthPercentage = 90;
        DataTable statusTable = new DataTable();
        statusTable = rs.getSeverity();
        Phrase title = new Phrase("");
        PdfPCell c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        title = new Phrase("LEGEND", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));
        c = new PdfPCell(title);
        c.Border = Rectangle.NO_BORDER;
        legendTable.AddCell(c);
        foreach (DataRow r in statusTable.Rows)
        {
            string statusName = r["statusName"].ToString();
            string statusDes = r["statusDescription"].ToString();
            int status_id = ToInt(r["status_id"].ToString());
            Phrase p1 = new Phrase(statusName, getFont(getColor(status_id), 8, "Arial"));
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;

            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            legendTable.AddCell(fc);
            p1 = new Phrase(statusDes, getFont(BaseColor.BLACK, 8, "Arial"));
            fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            legendTable.AddCell(fc);
        }

        return legendTable;
    }
    protected Paragraph getFirstPage()
    {
        Paragraph pr = new Paragraph();
        //pr.Font=getFont(BaseColor.BLACK,
        pr.Add(new Chunk("Vibration Survey & Report", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 18)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Vibration Monitoring", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Vibration analysis is a predictive maintenance method, which allows for early problem identification in active machines and is the most effective machine condition monitoring technique. Early detection of gear tooth wear, bearing deterioration, shaft misalignment, structural looseness, imbalance, cavitation, and all other correctable problems allows planned adjustment and repairs to equipment. This avoids costly breakdown repairs and disruption to operations. I2i uses latest tri-axial technology to collect data from all three planes simultaneously. This makes our machine assessment reports not only more accurate than our competitors but also allows for faster data acquisition and greater access to your plant and equipment from a single point location.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Survey and Data Collection", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("An i2i engineer will visit your site to carryout a survey and collect data and samples as required at the pre-arranged time. A preliminary analysis rs of any significant defects found and course of action will be printed and made available for discussion before the engineer leaves the site.  Site time may vary depending on how long it takes to survey the equipment due to its operational availability including both vehicular and safe plant access", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Analysis and Reporting", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Once collected, the data is analysed by our trained engineers and a preliminary rs is generated that identifies any OUT of LIMIT equipment faults and problem rectification while our engineers are still on site.  The data is then transferred to our Brisbane office for further analysis. This includes various techniques such as Narrow Band Alarms, RMS trends; Crest Factor (intensity), Statistical Process Control, Phase Relationship and Demodulation are used in every reading to assist the analysis. ", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("The report lists all the client’s machines (any un-surveyed are still listed, but Machine un-surveyed is entered under that machine). For each machine, the rs details any problems found and their severity, as well as any recommended corrective actions.  A full rs is then emailed within (3) Three days in PDF format, with a bound hard copy posted out to the client or client’s representative.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("Equipment", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("DLI Engineering DCX XRT PC based portable Four Channel data collection unit and analyser, serial number 556; DLI Engineering accelerometer, model N0 9938-7-NC-DLI serial number S/N 1223", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10)));
        pr.Add(Chunk.NEWLINE);
        pr.Add(Chunk.NEWLINE);
        pr.Add(new Chunk("General Layout of each page", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12)));
        pr.Add(Chunk.NEWLINE);
        Chunk chunk = new Chunk("A numbered list of equipment is generally shown on each page. The “equipment”, “component” and “criticality level” is detailed and colour coded next to each component surveyed. The headings can include descriptions requested by the client, or in the absence of this a convenient designation is made by the analyst.  A reference filename is also given for the report stored on the i2i computer system for future reference if required.", new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 10));
        pr.Add(chunk);
        pr.Alignment = Element.ALIGN_JUSTIFIED;
        pr.SpacingAfter = 0;
        pr.SpacingBefore = 0;
        pr.Leading = 13;
        return pr;

    }
    protected PdfPTable setTableInfo(ArrayList info, float width)
    {
        PdfPTable tableInfo = new PdfPTable(2);
        Chunk ck;


        Font font1;
        tableInfo.TotalWidth = width;
        for (int i = 0; i < 16; i++)
        {
            Phrase p1 = new Phrase();
            switch (i)
            {
                case 0:
                case 2:
                case 4:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 1:
                case 3:
                case 5:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 11);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 13:
                case 15:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10.5f);
                    String address = info[i].ToString();
                    String t;
                    int index = 0;
                    int count = 0;
                    while (true)
                    {
                        count = address.IndexOf(';', index);
                        if (count == -1)
                        {
                            ck = new Chunk(address.Substring(index).Trim(), font1);
                            p1.Add(ck);
                            break;
                        }
                        t = address.Substring(index, count - index).Trim();
                        index = count + 1;
                        ck = new Chunk(t, font1);
                        p1.Add(ck);
                        p1.Add(Chunk.NEWLINE);

                    }
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                case 12:
                case 14:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 10);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
                default:
                    font1 = new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 9.5f);
                    ck = new Chunk(info[i].ToString(), font1);
                    p1.Add(ck);
                    p1.Add(Chunk.NEWLINE);
                    p1.Add(Chunk.NEWLINE);
                    break;
            }
            PdfPCell fc = new PdfPCell(p1);
            fc.HorizontalAlignment = Element.ALIGN_LEFT;
            fc.MinimumHeight = 0f;
            fc.Border = Rectangle.NO_BORDER;
            fc.VerticalAlignment = Element.ALIGN_LEFT;
            if ((i > 5) && (i < 10))
            {
                // fc.SetLeading(0, 1.0f);
                fc.FixedHeight = 13;

            }
            else
                fc.MinimumHeight = 0;
            fc.PaddingBottom = 0.1f;
            fc.PaddingTop = 0.1f;
            tableInfo.AddCell(fc);
        }
        return tableInfo;

    }
    protected Font getFont(BaseColor color, float size, string type)
    {
        Font font = new Font();
        font.Color = color;//BaseColor.BLUE;
        font.Size = size;// 6f;
        font.SetFamily(type);//"Arial");
        return font;
    }
    protected DataTable getSelectedSites()
    {
        //selectedClient_id= 
        DataTable selectedSites = new DataTable();
        selectedSites.Columns.Add("siteName", typeof(string));
        selectedSites.Columns.Add("site_id", typeof(int));
        ReportServices rs = new ReportServices();
        selectedSites = rs.getSiteByCLientID(selectedClient_id);
        return selectedSites;
    }
    protected DataTable getSelectedStatus()
    {
        DataTable selectedStatus = new DataTable();
        selectedStatus.Columns.Add("statusName", typeof(string));
        selectedStatus.Columns.Add("status_id", typeof(int));
        ReportServices rs = new ReportServices();
        selectedStatus = rs.getSeverity();
        return selectedStatus;
    }
    protected string getShortName(string name)
    {
        string name1 = name.Trim();
        //int length = name.Length;
        string shorname = "";
        int ix = 0;
        shorname = shorname + name.Substring(0, 1).ToString().ToUpper();
        name1 = name.Substring(1);
        int index = index = name1.IndexOf(" ", ix);
        while (index != -1)
        {

            name1 = name1.Substring(index).Trim();
            shorname = shorname + name1.Substring(0, 1);
            index = name1.IndexOf(" ", ix);
        }
        return shorname;
    }
    protected BaseColor getColor(int status_id)
    {
        switch (status_id)
        {
            case 1: return BaseColor.GREEN;
            case 2: return BaseColor.YELLOW;
            case 3: return BaseColor.ORANGE;
            case 4: return BaseColor.RED;
            case 5: return BaseColor.BLUE;
            default: return BaseColor.BLACK;
        };


    }

    protected void FullReport_Button_Click(object sender, EventArgs e)
    {
        Client selectedClient = new Client();
        string selectedDate = "";
        Document document = new Document(PageSize.A4, 120, 85, 83, 125);
        headerfooter hf = new headerfooter();
        UserServices us = new UserServices();
        string ClientParentName = "";

        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        int dateIndex = 0;
        System.DateTime str_date = new DateTime();
        selectedClient = us.getClientByID(selectedClient_id);

        string selectedClientName = selectedClient.ClientName;

        try
        {

            selectedDate = DropDownList1.SelectedValue.Substring(0, DropDownList1.SelectedValue.IndexOf(" ")).Trim();
            str_date = DateTime.Parse(selectedDate, System.Globalization.CultureInfo.CreateSpecificCulture("en-AU").DateTimeFormat);

            dateIndex = DropDownList1.Items.Count - DropDownList1.SelectedIndex;//Request.QueryString["selectedDate"].ToString();

        }
        catch (Exception ex)
        {
            Console.Write(ex);
            // MessageBox.Show("No report available");

        }
        // step 2: we create a writer that listens to the document
        String path1 = Server.MapPath("Report");
        String p = Server.MapPath("Images");

        String path = path1 + "/Template.pdf";


        int ok = 0;
        while (ok != -1)
        {

            try
            {

                writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
                ok = -1;
            }
            catch (Exception)
            {
                ok++;
                path = path1 + "/Template" + ok.ToString() + ".pdf";
            }
        }


        Rectangle page = document.PageSize;
        // document.SetMargins(120, 90, 83, 30);
        document.SetMargins(120, 20, 83, 125);

        hf.setHeader(p + "/logoi2i.png", page.Width + 35, Element.ALIGN_CENTER, Rectangle.NO_BORDER, 75);
        hf.setFooter(page.Width);

        PdfPTable head = hf.Head;
        PdfPTable foot = hf.Foot;

        try
        {

            document.Open();

            // Add header for first page
            head.WriteSelectedRows(0, -1, 0, 820, writer.DirectContent);
            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
            if (ClientDetails.ParentClientID != 0)
            {
                ClientParentName = "" + us.getClientByID(ClientDetails.ParentClientID).ClientName;
            }
            else
                ClientParentName = ClientDetails.ClientName;
            title.Add(ClientParentName + " - Table" + dateIndex + " - " + selectedClientName); // + " Sites";
            title.Add("Vibration Analysis Report");
            title.Add(selectedDate);

            for (int i = 0; i < 3; i++)
            {
                Phrase t = new Phrase((String)title[i]);
                pa = new Paragraph(t);
                if (i == 0)
                    pa.Leading = 110;
                else
                    pa.Leading = 20;
                pa.Alignment = Element.ALIGN_CENTER;
                document.Add(pa);


            }
            string fileName = "" + selectedClient.ClientID + "-VA-" + getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";
            PdfPTable information = new PdfPTable(2);
            infor.Add("Engineer");
            infor.Add("Paul Clibbon");
            infor.Add("Report Filename");
            infor.Add(fileName);
            infor.Add("Report Distribution");
            infor.Add(selectedClient.ContactPerson);
            infor.Add("Phone");
            infor.Add(selectedClient.PhoneMobile.ToString());
            infor.Add("Fax");
            infor.Add(selectedClient.Fax.ToString());
            infor.Add("Email");
            infor.Add(selectedClient.Email);
            infor.Add("Address");
            infor.Add(selectedClient.Address);
            infor.Add("Report Distribution: Email reports in PDF format to:  ");
            infor.Add(selectedClient.DistributedEmail);
            information = setTableInfo(infor, page.Width - 80);
            information.HorizontalAlignment = Element.ALIGN_CENTER;
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(information);
            /* PdfPTable legend = new PdfPTable(2);
             legend = setLegendTable(page.Width);
             legend.HorizontalAlignment = Element.ALIGN_LEFT;
             document.Add(legend);           */


            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            document.Add(Chunk.NEWLINE);
            // document.Add(information);
            PdfPTable legend = new PdfPTable(2);
            legend = setLegendTable(page.Width);
            legend.HorizontalAlignment = Element.ALIGN_LEFT;
            document.Add(legend);

            // add new page
            document.SetMargins(120, 76, 83, 125);
            document.NewPage();

            //set first page 
            Paragraph firstPage = getFirstPage();
            document.Add(firstPage);
            document.NewPage();

            // set event automatically generate header for all next pages
            _events ev = new _events(p);
            writer.PageEvent = ev;
            DataTable selectedSites = new DataTable();
            DataTable selectedStatus = new DataTable();
            selectedSites.Columns.Add("siteName", typeof(string));
            selectedSites.Columns.Add("site_id", typeof(int));
            selectedStatus.Columns.Add("statusName", typeof(string));
            selectedStatus.Columns.Add("status_id", typeof(int));

            selectedSites = getSelectedSites();

            selectedStatus = getSelectedStatus();

            DataTable MachinesOfSites = new DataTable();
            ReportServices r = new ReportServices();
            MachinesOfSites = r.getMachineOfSites(selectedSites);
            DataTable componentsOfSites = new DataTable();
            componentsOfSites = r.getComponentsByMachinesAndStatusByDate(MachinesOfSites, selectedStatus, str_date);
            int num = componentsOfSites.Rows.Count;
            int index = 0;
            int listCount = 1;
            foreach (DataRow site in selectedSites.Rows)
            {
                String siteName = site["siteName"].ToString();
                string siteID = site["site_id"].ToString();
                bool haveValue = false;
                Phrase content = new Phrase(siteName, getFont(BaseColor.BLACK, 16f, "Arial"));
                Paragraph contentPa = new Paragraph(content);
                contentPa.Leading = 10;
                // contentPa.Font = 
                contentPa.Alignment = Element.ALIGN_CENTER;
                document.Add(contentPa);
                index++;
                int count = 0;
                string machineType = "";

                DataRow[] machinesOfSite = MachinesOfSites.Select("site_id = " + siteID.Trim(), "MachineType_name DESC");

                if (machinesOfSite.Length == 0)
                {
                    string noValue = " No component met the search criteria!";
                    content = new Phrase(noValue, getFont(BaseColor.BLACK, 12f, "Arial"));
                    contentPa = new Paragraph(content);
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(contentPa);
                    document.NewPage();
                    continue;
                }
                List componentList = new List(List.ORDERED);
                bool firstMachine = true;
                foreach (DataRow row in machinesOfSite)
                {
                    string machine_id = row["Machine_id"].ToString();
                    string ma_id = row["machine_id"].ToString();
                    DataRow[] componentsOfMachine = componentsOfSites.Select("machine_id= " + machine_id.Trim(), "component_id DESC");
                    if (componentsOfMachine.Length == 0)
                        continue;
                    //add machine type
                    haveValue = true;
                    if (machineType != row["MachineType_name"].ToString())
                    {
                        if (firstMachine == false)
                        {
                            content = new Phrase(machineType, getFont(BaseColor.BLUE, 14f, "Arial"));
                            contentPa = new Paragraph(content);
                            contentPa.Alignment = Element.ALIGN_CENTER;
                            document.Add(Chunk.NEWLINE);
                            document.Add(contentPa);
                            document.Add(Chunk.NEWLINE);
                            document.Add(componentList);
                        }
                        machineType = row["MachineType_name"].ToString();
                        count++;
                        componentList = new List(List.ORDERED);
                        componentList.First = listCount;
                        firstMachine = false;
                    }
                    // name of machine

                    string stt = "";
                    string fname = "";
                    string componentName = "";
                    string component_id = "0";
                    string comment = "";
                    // get components of machine
                    bool first = true;
                    string machineName = "";
                    Phrase statusName = new Phrase("");

                    foreach (DataRow component in componentsOfMachine)
                    {

                        if (component_id != component["component_id"].ToString())
                        {
                            if (first != true)
                            {

                                iTextSharp.text.ListItem item =
                                   new iTextSharp.text.ListItem("" + machineName + "-" + componentName + " ", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));

                                // content = new Phrase(" "+fname,getFont(BaseColor.RED,12,"Arial"));
                                item.Add(statusName);//,getFont(BaseColor.RED,12,"Arial"));
                                item.Add(Chunk.NEWLINE);
                                content = new Phrase(comment, new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 11));//getFont(BaseColor.BLACK,11,"Arial"));
                                contentPa = new Paragraph(content);
                                contentPa.Alignment = Element.ALIGN_JUSTIFIED;
                                item.Add(contentPa);
                                item.Add(Chunk.NEWLINE);

                                componentList.Add(item);
                                listCount++;
                                fname = "";
                                statusName = new Phrase("");


                            }
                            component_id = component["component_id"].ToString();
                            machineName = row["MachineName"].ToString();
                            componentName = component["componentName"].ToString();

                            comment = component["comments"].ToString();
                            fname = component["faultName"].ToString();
                            stt = component["status_id"].ToString();
                            Chunk c = new Chunk(fname, getFont(getColor(ToInt(stt)), 12, "Arial"));
                            statusName = new Phrase("");
                            statusName.Add(c);
                            first = false;

                        }
                        else
                        {
                            if (fname != "")
                            {
                                Chunk c = new Chunk("/", getFont(BaseColor.BLACK, 12, "Arial"));
                                statusName.Add(c);
                            }
                            // fname=fname+component["faultName"].ToString();
                            fname = component["faultName"].ToString();
                            stt = component["status_id"].ToString();
                            Chunk c1 = new Chunk(fname, getFont(getColor(ToInt(stt)), 12, "Arial"));
                            statusName.Add(c1);
                        }

                    }
                    iTextSharp.text.ListItem item1 =
                                   new iTextSharp.text.ListItem("" + machineName + "-" + componentName + " ", new Font(BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1250, false), 12));
                    //content = new Phrase(" " + fname, getFont(BaseColor.RED, 12, "Arial"));
                    item1.Add(statusName);//,getFont(BaseColor.RED,12,"Arial"));
                    item1.Add(Chunk.NEWLINE);
                    content = new Phrase(comment, new Font(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1250, false), 11));//getFont(BaseColor.BLACK, 11, "Arial"));
                    contentPa = new Paragraph(content);
                    contentPa.Alignment = Element.ALIGN_JUSTIFIED;
                    item1.Add(contentPa);
                    item1.Add(Chunk.NEWLINE);

                    componentList.Add(item1);
                    listCount++;
                    statusName = new Phrase("");
                    fname = "";
                }
                content = new Phrase(machineType, getFont(BaseColor.BLUE, 14f, "Arial"));
                contentPa = new Paragraph(content);
                contentPa.Alignment = Element.ALIGN_CENTER;
                document.Add(Chunk.NEWLINE);
                document.Add(contentPa);
                document.Add(Chunk.NEWLINE);
                document.Add(componentList);
                if (haveValue == false)
                {
                    string noValue = " No component met the search criteria!";
                    content = new Phrase(noValue, getFont(BaseColor.BLACK, 12f, "Arial"));
                    contentPa = new Paragraph(content);
                    contentPa.Alignment = Element.ALIGN_CENTER;
                    document.Add(Chunk.NEWLINE);
                    document.Add(Chunk.NEWLINE);
                    document.Add(contentPa);
                }
                document.NewPage();

            }
            document.Close();

            // set name for attact file


            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/pdf";
            Response.WriteFile(path);
            Response.Flush();
            Response.End();
            Response.Clear();

        }
        catch (Exception ee)
        {
            Console.Error.WriteLine(ee.StackTrace);
            Console.Error.WriteLine(ee.Message);

            if (ee.InnerException != ee)
            {

                // Console.Error.WriteLine(ee.InnerException.Message);
            }
        }



        // End of Thao









        /*  String sel_date = DropDownList1.SelectedValue;//DropDownListDate.DataTextField;
        // Response.Redirect("popup.aspx", "_blank");
        String clientID = Request.QueryString["client_id"];

        String selectedDate = DropDownList1.SelectedValue.Substring(0, 10);// DropDownListDate.SelectedValue.Substring(0, 10);
        //String site_url = "FullReport.aspx?clientID=" + clientID +"&d=" + selectedDate ;
        //Page.RegisterStartupScript("Window",  "<script language=\"javascript\">window.open('" + site_url + "','_blank','width=800,height=600,left=200,top=200');</script>");

        //Full_Report_Button.Attributes.Add("onclick", "window.open('Welcome.aspx'); return false;");
        CreateConn objcon = new CreateConn();
        string query_client = "SELECT clientName, contactPerson, phoneWork, email FROM Clients WHERE client_id='" + clientID + "'";
        DataTable dt_client = objcon.SQLConnDataTable(query_client);

        string strBody = "<html>" +
           "<body>";

        foreach (DataRow dr in dt_client.Rows)
        {
            strBody += "<div style='text-align:center; font-size: 28px' >" + dr["clientName"].ToString() + "</div>";
            strBody += "<br/> <p style='text-align:center; font-size: 14px; font-weight: bold' > Vibration Analysis Report </p>";
            strBody += "<p style='text-align:center;'> Engineer: Paul Clibbon </p> ";
            strBody += "<p style='text-align:center;' > Report Distribution: " + dr["contactPerson"].ToString() + " </p> ";
            strBody += "<p style='text-align:center;'> Phone: (07) " + dr["phoneWork"].ToString() + " </p> ";
            strBody += "<p style='text-align:center;'> Email : " + dr["email"].ToString() + "</p> ";
        }
        strBody += "<br/>";
        strBody += "<br/>";
        strBody += "<br/>";
        strBody += "<br/>";
        strBody += "<br/>";
        strBody += "<br/>";
        strBody += "<p style='font-weight: bold' >LEGEND</p>";
        strBody += "<font  color='green'>Normal</font  <span style='font-size: 10px;'>  Comment; minor problem may exist </span>"; strBody += "<br/>";
        strBody += "<font  color='#FFFF00'>Abnormal</font  <span style='text-align:center; font-size: 10px;'>  Minor problem; identified further monitor for any increase in severity at next "
        + "scheduled survey interval.</span>"; strBody += "<br/>";
        strBody += "<font  color='#F88017'>Moderate</font> <span style='font-size: 10px;'>  Definite problem; no immediate danger of failure is indicated but corrective action recommended when scheduling permits / or additional monitoring required.</span>";
        strBody += "<br/>";
        strBody += "<font  color='red'>Severe</font>  <span style='font-size: 10px;'>  Definite problem; equipment may continue to operate but corrective action should be scheduled ASAP.</span>";
        strBody += "<br/><br/><br/><br/>";

        objcon = new CreateConn();
        string query_site = "SELECT siteName, clientName, contactPerson, phoneWork, email FROM Sites s, Clients c WHERE c.client_id = s.client_id and c.client_id='1005'";
        DataTable dt_sites = objcon.SQLConnDataTable(query_site);

        foreach (DataRow dr in dt_sites.Rows)
        {
            strBody += "<div style='margin-left:100px; font:24px; page-break-before:always;'> " + dr["siteName"].ToString() + "</div><br/> <br/> <br/>";
            objcon = new CreateConn();
            string query_machine = "select machineName, machine_id from Sites s, Machines m " +
            "where s.site_id = m.site_id AND s.siteName = '" + dr["siteName"].ToString() + "'";
            DataTable dt_machine = objcon.SQLConnDataTable(query_machine);

            foreach (DataRow dr_machine in dt_machine.Rows)
            {
                //should change the content....Thao
                objcon = new CreateConn();
                string query_component = "SELECT machineName, componentName FROM Machines m, Components c " +
                "WHERE m.machine_id = c.machine_id AND m.machineName = '" + dr_machine["machineName"].ToString() + "'";
                DataTable dt_component = objcon.SQLConnDataTable(query_component);

                foreach (DataRow dr_component in dt_component.Rows)
                {
                    strBody += "<div>";
                    strBody += "<p style='font-weight:bold'>" + dr_component["machineName"].ToString() + " - " + dr_component["componentName"].ToString() + " <font  color='green'>Normal</font>";
                    strBody += "</p>";
                    strBody += "<span>No faults detected, no immediate problems are expected, re-survey in four months to further monitor any change in condition.</span>";
                    strBody += "<br/>";
                    strBody += "</div>";
                }
            }
        }

        strBody += "</body>" + "</html>";

        string fileName = "VibrationReport.doc";
        // You can add whatever you want to add as the HTML and it will be generated as Ms Word docs
        Response.AppendHeader("Content-Type", "application/msword");
        Response.AppendHeader("Content-disposition", "attachment; filename=" + fileName);
        Response.Write(strBody);*/




    }
    protected void Click_FullReport2(object sender, EventArgs e)
    {
        // Client selectedClient = new Client();
        string selectedDate = "";
        Document document = new Document(PageSize.A4, 120, 85, 83, 125);
        headerfooter hf = new headerfooter();
        UserServices us = new UserServices();
        string ClientParentName = "";

        selectedClient_id = ToInt(DropDownClientList.SelectedValue);
        int dateIndex = 0;
        //  selectedClient = us.getClientByID(selectedClient_id);

        //  string selectedClientName = selectedClient.ClientName;

        try
        {
            selectedDate = DropDownList1.SelectedValue.Substring(0, 10);
            dateIndex = DropDownList1.Items.Count - DropDownList1.SelectedIndex;//Request.QueryString["selectedDate"].ToString();

        }
        catch (Exception ex)
        {
            Console.Write(ex);
            // MessageBox.Show("No report available");

        }
        // step 2: we create a writer that listens to the document
        String path1 = Server.MapPath("Report");
        String p = Server.MapPath("Images");

        String path = path1 + "/Template.pdf";


        int ok = 0;
        while (ok != -1)
        {

            try
            {

                writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.Create));
                ok = -1;
            }
            catch (Exception)
            {
                ok++;
                path = path1 + "/Template" + ok.ToString() + ".pdf";
            }
        }


        Rectangle page = document.PageSize;
        // document.SetMargins(120, 90, 83, 30);
        document.SetMargins(120, 20, 83, 125);

        hf.setHeader(p + "/logoi2i.png", page.Width + 35, Element.ALIGN_CENTER, Rectangle.NO_BORDER, 75);
        hf.setFooter(page.Width);

        PdfPTable head = hf.Head;
        PdfPTable foot = hf.Foot;

        try
        {

            document.Open();

            // Add header for first page
            head.WriteSelectedRows(0, -1, 0, 820, writer.DirectContent);
            foot.WriteSelectedRows(0, -1, 0, 80, writer.DirectContent);
            if (ClientDetails.ParentClientID != 0)
            {
                ClientParentName = "" + us.getClientByID(ClientDetails.ParentClientID).ClientName;
            }
            else
                ClientParentName = ClientDetails.ClientName;
            title.Add(ClientParentName + " - Table" + dateIndex + " - ");// + selectedClientName); // + " Sites";
            title.Add("Vibration Analysis Report");
            title.Add(selectedDate);

            for (int i = 0; i < 3; i++)
            {
                Phrase t = new Phrase((String)title[i]);
                pa = new Paragraph(t);
                if (i == 0)
                    pa.Leading = 110;
                else
                    pa.Leading = 20;
                pa.Alignment = Element.ALIGN_CENTER;
                document.Add(pa);


            }
            //  string fileName = "" + selectedClient.ClientID + "-VA-" + getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";
            string fileName = "" + "-VA-";// +getShortName(selectedClient.ClientName) + "-" + dateIndex + ".pdf";


            document.Close();

            // set name for attact file


            Response.Clear();
            Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
            Response.ContentType = "application/pdf";
            Response.WriteFile(path);
            Response.Flush();
            Response.End();
            Response.Clear();

        }
        catch (Exception ee)
        {
            Console.Error.WriteLine(ee.StackTrace);
            Console.Error.WriteLine(ee.Message);

            if (ee.InnerException != ee)
            {

                // Console.Error.WriteLine(ee.InnerException.Message);
            }
        }



        // End of Thao
    }
    protected void CustomReport_Button_Click(object sender, EventArgs e)
    {
        Server.Transfer("CustomReport.aspx");//?id=" + machineid );//+ "&client_id=" + client_id );//+ "&selectedDate=" + selectedDate);
        //
    }
    protected void Data_Sheet_Button_Click(Object sender, EventArgs e)
    {
        String machineid = Request.QueryString["id"];
        MACHINEID = ToInt(machineid);
        MACHINENAME = Request.QueryString["machineName"];
        Server.Transfer("TechnicalDataSheets.aspx");//?id=" + machineid);//+ "&selectedDate=" + selectedDate);

    }
    protected void BindData(String machineID)
    {
        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);

        try
        {
            con.Open();
            string query = "SELECT siteName, machineName, photo" +
                    " FROM  Sites INNER JOIN" +
                    " Machines ON Sites.site_id = Machines.site_id" +
                    " WHERE (Machines.machine_id = " + machineID + ")";
            SqlDataAdapter sda = new SqlDataAdapter(query, con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            sitename.Text = dt.Rows[0]["siteName"].ToString();
            SITENAME = sitename.Text.ToString();
            machinename.Text = dt.Rows[0]["machineName"].ToString();


            //setting the Machine Image
            string path = Server.MapPath("../photos/" + dt.Rows[0]["photo"].ToString());
            System.Drawing.Image image = System.Drawing.Image.FromFile(path, true);
            ImageEditor objimg = new ImageEditor();
            int height = 0;
            int width = 0;
            if (objimg.isPortrait(image))
            {
                height = 160;
                width = 120;
            }
            else
            {
                height = 120;
                width = 160;
            }
            //machinePhoto.Attributes.Add("Width", Convert.ToString(width));
            //machinePhoto.Attributes.Add("Height", Convert.ToString(height));
            //machinePhoto.ImageUrl = "../photos/" + dt.Rows[0]["photo"].ToString();
            photoHyperLink.Attributes.Add("href", "../photos/" + dt.Rows[0]["photo"].ToString());

            if (dt.Rows[0]["photo"].ToString() == "NotAvailable.jpg")
            {
                photoHyperLink.Visible = false;
            }

            con.Close();
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }

        try
        {
            con.Open();
            string queryDate = "SELECT dateRecorded" +
                   " FROM ComponentStatus";

            SqlDataAdapter date_sda = new SqlDataAdapter(queryDate, con);
            DataTable date_dt = new DataTable();
            date_sda.Fill(date_dt);

            /*    string component_query = "SELECT componentName, statusName, comments, statusDescription, commentDescription" +
                        " FROM  Components,  ComponentStatus, Status, StandardComments " +
                        " WHERE Components.component_id = ComponentStatus.component_id " +
                        " AND ComponentStatus.status_id = Status.status_id " +
                        " AND ComponentStatus.comment_id = StandardComments.comment_id " +
                        " AND Components.machine_id = " + machineID;
                */

            string component_query = "SELECT Components.componentName,Components.component_id, ComponentStatus.status_id, ComponentStatus.comments" +
                                  " FROM            Components INNER JOIN" +
                                  " ComponentStatus ON Components.component_id = ComponentStatus.component_id" +
                                  " WHERE        (Components.machine_id =" + machineID + ")";// AND (ComponentStatus.dateRecorded = CONVERT(datetime, '" + currDate + "', 103))";

            SqlDataAdapter component_sda = new SqlDataAdapter(component_query, con);
            DataTable component_dt = new DataTable();
            component_sda.Fill(component_dt);

            string col = "#00FF00";
            ComponentName1.Text = component_dt.Rows[0]["componentName"].ToString();

            if (ComponentName1.Text.ToString().EndsWith("box"))
            {
                string component_id = component_dt.Rows[0]["component_id"].ToString();
                HyperLink1Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;
                HyperLink1Oil.Visible = true;

            }
            col = ConvertToColor(component_dt.Rows[0]["statusName"].ToString());
            CurrentLabel1.ForeColor = System.Drawing.Color.FromName(col);
            Description1.Text = component_dt.Rows[0]["comments"].ToString();

            if (ComponentName1.Text != null)
            {
                Component1.Visible = true;
            }
            ComponentName2.Text = component_dt.Rows[1]["componentName"].ToString();
            col = ConvertToColor(component_dt.Rows[1]["statusName"].ToString());
            CurrentLabel2.ForeColor = System.Drawing.Color.FromName(col);
            Description2.Text = component_dt.Rows[1]["comments"].ToString();
            if (ComponentName2.Text != null)
            {
                Component2.Visible = true;
            }
            if (ComponentName2.Text.ToString().EndsWith("box"))
            {
                string component_id = component_dt.Rows[1]["component_id"].ToString();
                HyperLink1Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;

                HyperLink2Oil.Visible = true;

            }
            ComponentName3.Text = component_dt.Rows[2]["componentName"].ToString();
            col = ConvertToColor(component_dt.Rows[2]["statusName"].ToString());
            CurrentLabel3.ForeColor = System.Drawing.Color.FromName(col);
            Description3.Text = component_dt.Rows[2]["comments"].ToString();
            if (ComponentName3.Text != null)
            {
                Component3.Visible = true;
            }
            if (ComponentName3.Text.ToString().EndsWith("box"))
            {

                string component_id = component_dt.Rows[2]["component_id"].ToString();
                HyperLink1Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;
                HyperLink3Oil.Visible = true;

            }
            ComponentName4.Text = component_dt.Rows[3]["componentName"].ToString();
            col = ConvertToColor(component_dt.Rows[3]["statusName"].ToString());
            CurrentLabel4.ForeColor = System.Drawing.Color.FromName(col);
            Description4.Text = component_dt.Rows[3]["comments"].ToString();
            if (ComponentName4.Text != null)
            {
                Component4.Visible = true;
            }
            if (ComponentName4.Text.ToString().EndsWith("box"))
            {
                string component_id = component_dt.Rows[3]["component_id"].ToString();
                HyperLink1Oil.NavigateUrl = "oilreport.aspx?id=" + machineID + "&component_id=" + component_id;
                HyperLink4Oil.Visible = true;
            }

            con.Close();

        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
    }

    //protected void submitButton_Click(object sender, EventArgs e) {

    //    String frm_date_submitted = WODateTime.Text.ToString();
    //    String frm_description = WODescription.Text.ToString();
    //    String frm_workorder_reference_no = WONumber.Text.ToString();
    //    String frm_machine_id = machineid.Text.ToString();
    //    string status = status_checkbox.Checked ? "1" : "0";

    //    CreateConn objcon = new CreateConn();
    //    string query = "INSERT INTO WorkOrders (workorder_reference_no, machine_id, description, date_submitted,status)"
    //           + " values ('" + frm_workorder_reference_no + "'," + frm_machine_id + ",'" + frm_description + "',convert(datetime,'" + frm_date_submitted + "', 103),'" + status + "')";

    //    objcon.SQLCmd(query);
    //    EditButton.Visible = true;
    //    wo_message.Text = "Work Order: " + WONumber.Text.ToString() + " Successfully created";
    //    //WODateTime.Enabled = false;
    //    //WONumber.Enabled = false; ;
    //    //WODescription.Enabled = false; ;
    //    //status_checkbox.Enabled = false;
    //    submitButton.Visible = false;
    //    //WODescription.Text = "";
    //    //WONumber.Text = "";
    //}
    //protected void defaultSearch_clicked(object sender, EventArgs e) {
    //    String keyword = keyword_TB.Text;
    //    if (keyword == "") {
    //        Response.Write("<script language=javascript> alert('Must Input W/O No.')</script>");
    //    } else {
    //        string query = "SELECT * FROM WorkOrders WHERE workorder_reference_no='" + keyword + "'";
    //        CreateConn obj = new CreateConn();
    //        DataTable dt = obj.SQLConnDataTable(query);
    //        foreach (DataRow dr in dt.Rows) {
    //            WODateTime.Enabled = true;
    //            WONumber.Enabled = true; ;
    //            WODescription.Enabled = true; ;
    //            status_checkbox.Enabled = true;
    //            UpdateButton.Visible = true;
    //            WODateTime.Text = dr["date_submitted"].ToString();
    //            WODescription.Text = dr["description"].ToString();
    //            status_checkbox.Checked = dr["status"].ToString() == "1" ? true : false;
    //            WONumber.Text = dr["workorder_reference_no"].ToString();
    //            WODateTime.Enabled = false;
    //            WONumber.Enabled = false; ;
    //            WODescription.Enabled = false; ;
    //            status_checkbox.Enabled = false;
    //            UpdateButton.Visible = false;
    //        }
    //    }


    //}
    //protected void preClicked(object sender, EventArgs e) {

    //    workorderID = getworkorderID(WONumber.Text);

    //    string query = "SELECT * FROM WorkOrders WHERE machine_id='" + Int32.Parse(machineid.Text) + "' and workorder_reference_no!='" + WONumber.Text + "' and workorder_id <'" + workorderID + "' order by date_submitted desc";
    //    CreateConn cc = new CreateConn();
    //    DataTable dt = cc.SQLConnDataTable(query);
    //    if (dt != null) {
    //        if (dt.Rows.Count > 0) {
    //            foreach (DataRow dr in dt.Rows) {
    //                string worderorderNo = dr["workorder_id"].ToString();
    //                string workorderRef = dr["workorder_reference_no"].ToString();
    //                WONumber.Text = workorderRef;
    //                WODateTime.Text = dr["date_submitted"].ToString();
    //                status_checkbox.Checked = dr["status"].ToString() == "1" ? true : false;
    //                WODescription.Text = dr["description"].ToString();
    //                submitButton.Visible = false;
    //                EditButton.Visible = true;
    //                wo_message.Text = "";

    //                break;
    //            }
    //        } else {
    //            //Response.Write("<script language=javascript> alert('No Next workorder exists')</script>");
    //            wo_message.Text = "No Previous workorder exists";
    //            //wo_message.ForeColor = "red";
    //        }
    //    }

    //}
    //protected void nextwoClicked(object sender, EventArgs e) {

    //    workorderID = getworkorderID(WONumber.Text);

    //    string query = "SELECT * FROM WorkOrders WHERE machine_id='" + Int32.Parse(machineid.Text) + "' and workorder_reference_no!='" + WONumber.Text + "' and workorder_id >'" + workorderID + "' order by date_submitted asc";
    //    CreateConn cc = new CreateConn();
    //    DataTable dt = cc.SQLConnDataTable(query);
    //    if (dt != null) {
    //        if (dt.Rows.Count > 0) {
    //            foreach (DataRow dr in dt.Rows) {
    //                string worderorderNo = dr["workorder_id"].ToString();
    //                string workorderRef = dr["workorder_reference_no"].ToString();
    //                WONumber.Text = workorderRef;
    //                WODateTime.Text = dr["date_submitted"].ToString();
    //                status_checkbox.Checked = dr["status"].ToString() == "1" ? true : false;
    //                WODescription.Text = dr["description"].ToString();
    //                submitButton.Visible = false;
    //                EditButton.Visible = true;
    //                wo_message.Text = "";
    //                break;
    //            }
    //        } else {
    //            //  Response.Write("<script language=javascript> alert('No previous workorder exists')</script>");
    //            wo_message.Text = "No Next workorder exists";

    //        }
    //    }

    //}

    //protected int getworkorderID(string referenceNo) {
    //    string query = "SELECT workorder_id FROM WorkOrders WHERE workorder_reference_no='" + WONumber.Text + "'";
    //    CreateConn ccobj = new CreateConn();
    //    DataTable dt = ccobj.SQLConnDataTable(query);
    //    if (dt.Rows.Count > 0) {
    //        foreach (DataRow dr in dt.Rows) {
    //            return this.workorderID = Int32.Parse(dr["workorder_id"].ToString());
    //            //Session["workorderid"] = workorderID;
    //        }
    //    }
    //    return 0;
    //}
    //protected void createbuttonclicked(object sender, EventArgs e) {
    //    WODateTime.Text = "";
    //    WONumber.Text = "";
    //    WODescription.Text = "";
    //    status_checkbox.Checked = false;
    //    UpdateButton.Visible = false;
    //    EditButton.Visible = false;
    //    submitButton.Visible = true;

    //}
    //protected void UpdateButton_Click(object sender, EventArgs e) {

    //    workorderID = (int)Session["workorderid"];
    //    string status = status_checkbox.Checked ? "1" : "0";
    //    string query = "Update WorkOrders Set workorder_reference_no='" + WONumber.Text + "',description='"
    //       + WODescription.Text + "',status = '" + status + "',date_submitted=convert(datetime,'" + WODateTime.Text + "', 103) WHERE "
    //       + "workorder_id='" + workorderID + "'";
    //    CreateConn cc = new CreateConn();
    //    cc.SQLConnDataTable(query);
    //    //WODateTime.Enabled = false;
    //    //WONumber.Enabled = false; ;
    //    //WODescription.Enabled = false; ;
    //    //status_checkbox.Enabled = false;
    //    UpdateButton.Visible = false;

    //}
    //protected void EditButton_click(object sender, EventArgs e) {
    //    WODateTime.Enabled = true;
    //    WONumber.Enabled = true; ;
    //    WODescription.Enabled = true; ;
    //    status_checkbox.Enabled = true;
    //    UpdateButton.Visible = true;
    //    string query = "SELECT workorder_id FROM WorkOrders WHERE workorder_reference_no='" + WONumber.Text + "'";
    //    CreateConn ccobj = new CreateConn();
    //    DataTable dt = ccobj.SQLConnDataTable(query);
    //    if (dt.Rows.Count > 0) {
    //        foreach (DataRow dr in dt.Rows) {
    //            this.workorderID = Int32.Parse(dr["workorder_id"].ToString());
    //            Session["workorderid"] = workorderID;
    //        }
    //    }
    //    //  this.workorderID = 
    //    //String frm_date_submitted = WODateTime.Text.ToString();
    //    //String frm_description = WODescription.Text.ToString();
    //    //String frm_workorder_reference_no = WONumber.Text.ToString();
    //    //String frm_machine_id = machineid.Text.ToString();

    //    //CreateConn objcon = new CreateConn();
    //    //string query = "INSERT INTO WorkOrders (workorder_reference_no, machine_id, description, date_submitted,status)"
    //    //        + " values ('" + frm_workorder_reference_no + "'," + frm_machine_id + ",'" + frm_description + "',convert(datetime,'" + frm_date_submitted + "', 103),0)";

    //    //objcon.SQLCmd(query);

    //    //wo_message.Text = "Work Order: " + WONumber.Text.ToString() + " Successfully created";
    //    //WODescription.Text = "";
    //    //WONumber.Text = "";
    //}
    //protected void searchbuttonClicked(object sender, EventArgs e) {
    //    String clientID = Request.QueryString["client_id"];
    //    Session["clientid"] = clientID;
    //    //String clientID = Request.QueryString["client_id"];
    //    //Session["clientid"] = clientID;







    //    Response.Redirect("Search_Workorder.aspx");
    //}
    protected void WorkOrder_Button_Click(object sender, EventArgs e)
    {
        Response.Redirect("Work_Orders.aspx");
    }
}
